/*
 * @Description: 
 * @Author: ldx
 * @Date: 2022-05-31 23:39:45
 * @LastEditors: ldx
 * @LastEditTime: 2022-07-13 22:39:31
 */
import * as THREE from 'three';
import chinas from './chinas.png'
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
/** 创建场景 */
const scene = new THREE.Scene();

// 创建光源
// 环境光，没有特定的方向
const ambientLight = new THREE.AmbientLight(0xff0000)
scene.add(ambientLight)
// 平行光，类似于生活中的太阳光
const directionalLight = new THREE.DirectionalLight(0xff0000, 1)
directionalLight.position.set(400, 200, 300)
scene.add(directionalLight)
/** 相机设置 */
const width = window.innerWidth; //窗口宽度
const height = window.innerHeight; //窗口高度
const k = width / height; //窗口宽高比
//创建相机对象
const camera = new THREE.PerspectiveCamera(45, k, 1, 100);
camera.position.set(0, 0, 3); //设置相机位置
camera.lookAt(scene.position); //设置相机方向(指向的场景对象)
/** 创建渲染器对象 */
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height); //设置渲染区域尺寸
// renderer.setClearColor(0x888888, 1); //设置背景颜色
document.body.appendChild(renderer.domElement); //body元素中插入canvas对象
// 创建一个立方缓冲几何体
const geometry = new THREE.PlaneBufferGeometry( 1, 1, 56, 56 )
const text = new THREE.TextureLoader().load(chinas)
// 创建材质
const material = new THREE.ShaderMaterial({
  vertexShader:`
    varying vec2 aUv;
    varying float deep;
    uniform float uTime;
    void main(){
      aUv = uv;
      vec4 modelPosition = modelMatrix * vec4(position,1.0);
      modelPosition.z = cos((modelPosition.x + uTime) * 10.0) * 0.05;
      modelPosition.z += sin((modelPosition.y + uTime) * 10.0) * 0.05;
      deep = modelPosition.z + 0.7;
      gl_Position = projectionMatrix * viewMatrix * modelPosition;
    }
  `,
  fragmentShader:`
    varying vec2 aUv;
    varying float deep;
    uniform sampler2D uTexture;
    void main(){
      vec4 textureColor = texture2D(uTexture,aUv);
      textureColor.rgb *= deep;
      gl_FragColor = textureColor;
    }
  `,
  uniforms:{
    uTime:{
      value:0
    },
    uTexture:{
      value:text
    }
  },
  side:THREE.DoubleSide
});
// 生成带有材质的物体
const cube = new THREE.Mesh( geometry, material );
// 把物体添加进场景中
scene.add( cube );

const controls = new OrbitControls(camera, renderer.domElement)
controls.addEventListener("change", () => {
  render()
}); //监听鼠标、键盘事件
// 渲染
function render(){
  renderer.render(scene, camera); //执行渲染操作
}
const clock = new THREE.Clock();
function animate(){
  const time = clock.getElapsedTime();
  material.uniforms.uTime.value = time
  render()
  requestAnimationFrame(animate)
}
animate()